//
//  GameViewController.m
//  GOGOTravel
//
//  Created by dllo on 16/2/1.
//  Copyright © 2016年 果果. All rights reserved.
//

#import "GameViewController.h"
#import "Game1TableViewCell.h"
#import "Game2TableViewCell.h"
#import "Game3TableViewCell.h"
#import "Game4TableViewCell.h"
#import "UMSocial.h"
#import "MapViewController.h"
#import "GameXiangQingViewController.h"
@interface GameViewController ()<UITableViewDataSource, UITableViewDelegate, UMSocialUIDelegate, Game1TableViewCellDelegate>
@property (nonatomic, retain) UIImageView *imageView2;

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, assign) CGFloat realHeight;
@property (nonatomic, retain) NSMutableArray *dataArr;/**<  数据数组 */
@property (nonatomic, retain) NSMutableArray *daysArr;/**<  装日程的数组 */

@property (nonatomic, retain) NSMutableArray *XiaZaiArrl;/**<  下载数据的数组 */


@end

@implementation GameViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)dealloc{
    [_imageView2 release];
    [_dataArr release];
    [_daysArr release];
    [_XiaZaiArrl release];
    [_tripId release];
    [_model release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.9 green:0.29 blue:0.44 alpha:1];
    self.view.backgroundColor = UIColorFromRGB(0xF0F0F0);
    self.daysArr = [NSMutableArray array];
    self.dataArr = [NSMutableArray array];
    [self createItem];
    
    [self createTabelView];
    
    [self handelData];
    
    
}
#pragma mark-跳到地图的代理协议

- (void)jumpToMap:(NSDictionary *)point{
    MapViewController *map = [[MapViewController alloc] init];
    
    map.point = point;
    map.arr = _daysArr;
    [self.navigationController pushViewController:map animated:YES];
    
    
    [map release];
}

- (void)createItem{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fenxiang.png"] style:UIBarButtonItemStylePlain target:self action:@selector(itemAction:)];
    
    
    UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-xiazai.png"] style:UIBarButtonItemStylePlain target:self action:@selector(item3Action:)];
    self.navigationItem.rightBarButtonItems = @[item,item3];
    
    UIBarButtonItem *item4 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-jiantouzuo.png"] style:UIBarButtonItemStylePlain target:self action:@selector(item4Action:)];
    self.navigationItem.leftBarButtonItem = item4;
}
#pragma mark-item实现方法
//分享
- (void)itemAction:(UIBarButtonItem *)item{
    
    
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
        /**
         Sns平台类，用`platformName`作为标识，指定显示名称、显示的图片，点击之后的响应。
         */
        snsPlatform.displayName = @"新浪";
        
        
        if (_dataArr.count > 0) {
            Game *model = [_dataArr firstObject];
            
            if (![model.name isEqual:@""]) {
                UMSocialSnsPlatform *snsPlatform2 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
                snsPlatform2.displayName = @"腾讯微博";
                
                NSString *result = [NSString stringWithFormat:@"#面包游记推荐# 迷恋大海的碧绿，渴望天空的湛蓝。希望有一天能拎着行囊，让自己的心随清风流浪。我在@面包旅行 发现了精彩游记「%@」，分享给大家共赏～", model.name];
                
                [UMSocialSnsService presentSnsIconSheetView:self
                                                     appKey:@"56d6f3dee0f55a29fb0029fd"
                                                  shareText:result
                                                 shareImage:nil
                                            shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToWechatSession,nil]
                                                   delegate:self];
                
            }
            
            
            
            
        }
}



- (void)item3Action:(UIBarButtonItem *)item{
    
        NSDictionary *dic = _model.data[0];
        
        Game *model = [_dataArr firstObject];
        
        NSString *Image = dic[@"cover_image_1600"];
        NSString *name = model.name;
        NSNumber *num = dic[@"id"];
        NSString *urlId = [num stringValue];
    
        
        
        NSMutableDictionary *XiaZai = [NSMutableDictionary dictionary];
        
        if (Image != nil && name != nil && urlId != nil) {
            [XiaZai setObject:Image forKey:@"image"];
            [XiaZai setObject:name forKey:@"name"];
            [XiaZai setObject:urlId forKey:@"urlId"];
            
        }
        
        
    
        
        
        
        
        //获取document路径
        NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        
        //拼接下载路径
        NSString *xiaZaiWenJian = [document stringByAppendingPathComponent:@"xiaZaiWenJianJia.plist"];
        //写入本地
        
        //先从路径中区数组
        NSMutableArray *arr1 = [NSMutableArray arrayWithContentsOfFile:xiaZaiWenJian];
        
        if (arr1.count == 0) {
            
            NSMutableArray *arr = [NSMutableArray array];
            [arr addObject:XiaZai];
            
            
            BOOL result = [arr writeToFile:xiaZaiWenJian atomically:YES];
            
            if (result) {
                NSLog(@"写入成功");
                
                [self createAlert1];
            }else{
                NSLog(@"写入失败");
            }
            
        }else{
        
            [arr1 addObject:XiaZai];
            
            BOOL result = [arr1 writeToFile:xiaZaiWenJian atomically:YES];
            
            if (result) {
                NSLog(@"写入成功");
                
                [self createAlert1];
                
            }else{
                NSLog(@"写入失败");
            }
            
            
        }
        
}
    
    

/** 创建alert */

- (void)createAlert {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已下载" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
}

- (void)createAlert1{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"下载成功" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];

    
    
    
}


- (void)item4Action:(UIBarButtonItem *)item{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createTabelView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    //注册
    [_tableView registerNib:[UINib nibWithNibName:@"Game1TableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Game1TableViewCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"Game2TableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Game2TableViewCell"];
    
   
    
}
#pragma mark-tableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _daysArr.count + 2;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row > 1) {
        Days *model = _daysArr[indexPath.row - 2];
        
        
        self.tabBarController.hidesBottomBarWhenPushed = YES;
        
        
        GameXiangQingViewController *gx = [[GameXiangQingViewController alloc] init];
        
        gx.model = model;
        
        [self presentViewController:gx animated:YES completion:^{
            
        }];
        
    }
    
}








- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        Game1TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Game1TableViewCell"];
        Game *model = [_dataArr firstObject];
        cell.model = model;
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.row == 1){
        Game2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Game2TableViewCell"];
        Game *model = [_dataArr firstObject];;
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
              return cell;
    }else{
        
        
        
        
        Days *model = _daysArr[indexPath.row - 2];
        
        //唯一的表示
        NSString *str = [NSString stringWithFormat:@"Game4TableViewCell%ld", (long)indexPath.row];
        
        Game4TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (!cell) {
            cell = [[Game4TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
        }
        
       
        cell.model = model;
        return cell;
  }
    
        
    
        
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    cell.layer.transform = CATransform3DMakeRotation(2, 0, 1, 0);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeRotation(0, 0, 0, 0);
    }];
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 350;
    }else if (indexPath.row == 1){
        return 200;
    }else{
       
        Days *model = _daysArr[indexPath.row - 2];
        
        //获取图片的真实高度
        NSDictionary *dInfo = model.photo_info;
        NSNumber *num1 = dInfo[@"h"];
        NSNumber *num2 = dInfo[@"w"];
        CGFloat height = [num1 floatValue];
        CGFloat width =  [num2 floatValue];
        _realHeight = 0;
        if ([num1 integerValue] > 0 && [num2 integerValue] > 0) {
            
            //缩放后宽度固定为335；
            CGFloat scale = width / ([UIScreen mainScreen].bounds.size.width - 20);
            _realHeight = height / scale;
            _imageView2.frame = CGRectMake(10, 50, [UIScreen mainScreen].bounds.size.width - 20, _realHeight);
            
           
            [_imageView2 sd_setImageWithURL:[NSURL URLWithString:model.photo] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];

        }
        
        NSString *str4 = model.text;
               //设置字体样式
        NSDictionary *att = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
        
        CGRect rect = [str4 boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 35, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:att context:nil];

        return _realHeight + 50 + 5 + rect.size.height+ 95;
        
    }
}

- (void)handelData{
    
   NSString *str = @"http://api.breadtrip.com/trips/2387320917/waypoints/?gallery_mode=1&sign=8a2a44eed37683f725d3761a8e3d1a70";
    
    
        NSString *url = [str stringByReplacingCharactersInRange:NSMakeRange(31, 10) withString:_tripId];
        
        [AFNetWorkingHandle GETRequestWithURLString:url completionWithSuccess:^(id result) {
            
            
            
            Game *model = [[Game alloc] initWithDic:result];
            [_dataArr addObject:model];
           
            
            NSArray *days = result[@"days"];
            
            for (NSDictionary *dic in days) {
                NSArray *waypoints = dic[@"waypoints"];
                for (NSDictionary *dic in waypoints) {
                    Days *model = [[Days alloc] initWithDic:dic];
                    [_daysArr addObject:model];
                }
            }
            
          
            
            [_tableView reloadData];
        } withFailure:^(id error) {
            
        }];
        
        
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
